from django.contrib.auth import views as auth_views
from django.contrib.auth import login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import HttpResponseRedirect, redirect, reverse
from django.views.generic import TemplateView, CreateView
from django.utils.translation import gettext_lazy as _
from django.views.generic.edit import UpdateView
from audit.models import AuditManagement
from django.urls import reverse_lazy

from .lib import template_path

from .. import forms, models

class LoginPortal(TemplateView):
    template_name = template_path('login_portal.html')

class LoginView(auth_views.LoginView):
    form_class = forms.AuthenticationForm
    template_name = template_path('login.html')

class SignUpView(CreateView):
    form_class = forms.UserRegistryForm
    template_name = template_path('signup.html')

    def get_context_data(self, **kwargs):
        code = self.request.GET.get("code")
        context = super().get_context_data(**kwargs)
        form = context['form']
        if code:
            form.initial['invite_code'] = code
        return context

    def form_valid(self, form):
        user = form.save()
        
        invite_code = form.cleaned_data['invite_code']
        if invite_code:
            invite_code.times_used += 1 # the max_uses is validated during form validation
            invite_code.save()

            am = AuditManagement.objects.get_for_object(user)
            am.status = "approved"
            am.save()

        login(self.request, user)
        return HttpResponseRedirect(reverse('user:signup1'))

class SignUpSupplementInfomationView(
    LoginRequiredMixin,
    UpdateView
):
    template_name = template_path('signup1.html')
    form_class = forms.UserRegistrySupplementInfomationForm
    success_url = reverse_lazy("user:signup2")
    
    def get_object(self, queryset=None):
        return self.request.user

class SignUpFinishWaittingRoomView( 
    LoginRequiredMixin,
    TemplateView
):
    template_name = template_path('signup2.html')
    
    def get_context_data(self, **kwargs):
        user = self.request.user
        context = super().get_context_data(**kwargs)
        context['am'] = AuditManagement.objects.get_for_object(user)
        return context
